package notes.java.juc.demo;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *  测试读写锁
 *  要求：
 *  线程间读取与写要有锁
 *  线程间写与写要有锁
 *  线程间读取与读取不用锁
 *  
 *  可以看出打印结果：
 *  读取时是最后一次写入的内容。
 */

public class K11_TestReadWriteLock {

	public static void main(String[] args) {
		final RWLock rwlock = new RWLock();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(int i=0; i<100; i++) {
					rwlock.read();
				}
			}
		}).start();;
		
		for(int i=0; i<10; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					rwlock.write(new Random().nextInt(1000));
				}
			}).start();;
		}
	}
}

class RWLock {
	private int num = 0; // 共享数据,读写要同时要用的
	
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // 读写锁
	
	// 读操作
	public void read() {
		try{
			lock.readLock().lock(); // 读锁定
			System.out.println(Thread.currentThread().getName() + "读取：" + this.num);
		}finally {
			lock.readLock().unlock();// 释放读锁
		}
	}
	
	// 写操作
	public void write(int num) {
		try{
			lock.writeLock().lock(); // 写锁定
			this.num = num;
			System.out.println(Thread.currentThread().getName() + "写数据 ：" + num);
		}finally {
			lock.writeLock().unlock();// 释放写锁
		}
	}
}